package com.ybkj.chat.utils;


import android.util.Log;

import org.apache.commons.codec.binary.Base64;

import java.security.InvalidKeyException;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;

/**
 * @ClassName RSAUtil
 */
public class RSAUtil {

    /**
     * RSA私钥
     */
    public static final String PRIVARE_KEY = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBANFNA6w89tbywnKk" +
            "6jFNYaXHiW0liTfovfQchSqv2nLWswP4pYTwB3s8dY7b3GnZuyOW/TYrfNHomqJY" +
            "XSxMS4B0h09h9sKitOywAsG2WyZydQSqbiw3TI29G2K3Yh8lGKd5IbCiBtvqr/dM" +
            "pPMSbq5EZzMdaIzmAnd2pGlrLkmpAgMBAAECgYAYrv185Z+yz+RwwtQ/xkF63KJv" +
            "ddrN9ivYyzhFRYH8wydPk5ZprCkltoait3kyHpR8aQUpy00oMEd0V/l9DO5mXC/P" +
            "bDPQ0WdkD85d3QDpWKJUyyWJDmTl3zZX7q4P6B0UCEw7ISyjOz1Ypv/lDSOjh3YM" +
            "AU2VLX+HUvOtiyZxAQJBAPJjmR+zOQFk2/s567B0z1fMW/3xu6RlgPe1H9ete/I8" +
            "WxAe3seFPhr50aY7ienvyrkypD7d2i/hSCA2bSXoniECQQDdDcPWpHws4cljUsRb" +
            "VDHB74abyB3nVQGSe9obsJPCDCeqWh19o9FrZiC8jWEstmESp72xNh8mdMHz7LoZ" +
            "OGqJAkAI1QA7W3h0SIyLduzTnS4A8P1ZH3nK37f3Tq4+WZ/uj6xxxe4wLva4XOn6" +
            "uKip0Yb9gI7ji4nrvLW4FsObYgKBAkEA04IfN1pNIlir7Cg+jzBhJ7I69wWkbzsr" +
            "9PAigkoTJyGgNmRhQV0kvQGMIz2XlEOxYDs1ysEBTzd6eR2x9v2/GQJARwTCk3Hh" +
            "EyFSEhN1N2E1OKoUi/i4jE5pRUHNSrAQmpQLDPH8PsKoe4DdDQ3A/Q8AVesJJqYh" +
            "WjujmkIXXRmOmw==";

    /**
     * RSA公钥
     */
    public static final String PUBLIC_KEY = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDJzd5JRK22xnZMFs4ULIhSeooLi7tqA" +
            "6islwxMRiwKISPd6b5uyu5kmuhTbUiD95G6JUNEwpnJcH8M9GI/M913aEDaSxIKluQ3k0fh" +
            "17sKQjJHKsDAltVBIPYgcE3seP8Yno1wVlVPwPPRIGREocsLqRrV6j4Ft0f+eBEk9KMF+QIDAQAB";

    /**
     * 签名算法
     */
    private static final String SIGNATURE_ALGORITHM = "SHA1withRSA";
    /**
     * 加密算法RSA
     */
    private static final String KEY_ALGORITHM = "RSA";

    /**
     * 公钥验签
     *
     * @param text      原字符串
     * @param sign      签名结果
     * @param publicKey 公钥
     * @return 验签结果
     */
    public static boolean verify(String text, String sign, String publicKey) {
        try {
            Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
            PublicKey key = KeyFactory.getInstance(KEY_ALGORITHM).generatePublic(new X509EncodedKeySpec(Base64.decodeBase64(publicKey)));
            signature.initVerify(key);
            signature.update(text.getBytes());
            return signature.verify(Base64.decodeBase64(sign));
        } catch (Exception e) {
            Log.e("验签失败:text={},sign={}", text + "  " + sign);
            Log.e("验签失败", e.toString());
        }
        return false;
    }

    /**
     * 签名字符串
     *
     * @param text       需要签名的字符串
     * @param privateKey 私钥(BASE64编码)
     * @return 签名结果(BASE64编码)
     */
    public static String sign(String text, String privateKey) {
        byte[] keyBytes = Base64.decodeBase64(privateKey);
        PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
        try {
            KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
            PrivateKey privateK = keyFactory.generatePrivate(pkcs8KeySpec);
            Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
            signature.initSign(privateK);
            signature.update(text.getBytes());
            byte[] result = signature.sign();
            return Base64.encodeBase64String(result);
        } catch (Exception e) {
            Log.e("签名失败,text={}", text, e);
        }
        return null;
    }


    /**
     * 公钥加密过程
     *
     * @param publicKey     公钥(BASE64编码)
     * @param plainTextData 明文数据
     * @return 密文 (BASE64编码)
     * @throws Exception 加密过程中的异常信息
     */
    public static String encrypt(String publicKey, String plainTextData) {
        if (publicKey == null) {
            Log.e("加密公钥为空", "加密公钥为空, 请设置");
            return null;
        }
        Cipher cipher = null;
        try {
            // 使用默认RSA
            cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
            // cipher= Cipher.getInstance("RSA", new BouncyCastleProvider());
            cipher.init(Cipher.ENCRYPT_MODE, getPublicKey(publicKey));
            byte[] output = cipher.doFinal(plainTextData.getBytes());
            return Base64.encodeBase64String(output);
        } catch (NoSuchAlgorithmException e) {
            Log.e("无此加密算法", e.toString());
        } catch (NoSuchPaddingException e) {
            Log.e("NoSuchPadding错误,请检查", e.toString());
        } catch (InvalidKeyException e) {
            Log.e("加密公钥非法,请检查", e.toString());
        } catch (IllegalBlockSizeException e) {
            Log.e("明文长度非法", e.toString());
        } catch (BadPaddingException e) {
            Log.e("明文数据已损坏", e.toString());
        } catch (Exception e) {
            Log.e("其他错误,请检查", e.toString());
        }
        return null;
    }

    /**
     * 私钥解密过程
     *
     * @param privateKey 私钥 (BASE64编码)
     * @param cipherData 密文数据(BASE64编码)
     * @return 明文
     * @throws Exception 解密过程中的异常信息
     */
    public static String decrypt(String privateKey, String cipherData) {
        if (privateKey == null) {
            Log.e("sign", "解密私钥为空, 请设置");
            return null;
        }
        Cipher cipher = null;
        try {
            // 使用默认RSA
            cipher = Cipher.getInstance("RSA");
            // cipher= Cipher.getInstance("RSA", new BouncyCastleProvider());
            cipher.init(Cipher.DECRYPT_MODE, getPrivateKey(privateKey));
            byte[] output = cipher.doFinal(Base64.decodeBase64(cipherData));
            return new String(output);
        } catch (NoSuchAlgorithmException e) {
            Log.e("无此解密算法", e.toString());
        } catch (NoSuchPaddingException e) {
            Log.e("NoSuchPadding错误,请检查", e.toString());
        } catch (InvalidKeyException e) {
            Log.e("解密私钥非法,请检查", e.toString());
        } catch (IllegalBlockSizeException e) {
            Log.e("密文长度非法", e.toString());
        } catch (BadPaddingException e) {
            Log.e("密文数据已损坏", e.toString());
        } catch (Exception e) {
            Log.e("其他错误,请检查", e.toString());
        }
        return null;
    }


    /**
     * 获取私钥
     *
     * @param privateKey 私钥字符串
     * @return
     */
    public static PrivateKey getPrivateKey(String privateKey) throws Exception {
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        byte[] decodedKey = Base64.decodeBase64(privateKey);
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(decodedKey);
        return keyFactory.generatePrivate(keySpec);
    }

    /**
     * 获取公钥
     *
     * @param publicKey 公钥字符串()
     * @return
     */
    public static PublicKey getPublicKey(String publicKey) throws Exception {
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        byte[] decodedKey = Base64.decodeBase64(publicKey);
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(decodedKey);
        return keyFactory.generatePublic(keySpec);
    }
}